import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:rfid/hive/hive_helper.dart';

import '../entity/setting_entity.dart';
import '../event/inventory_rfid_event.dart';
import '../main.dart';
import '../socket/socket.dart';
import '../util/toast_util.dart';
import '../widget/focus_killer.dart';


class SettingCommon extends StatefulWidget {
  const SettingCommon({Key? key}) : super(key: key);

  @override
  State<SettingCommon> createState() => _SettingCommonState();
}

class _SettingCommonState extends State<SettingCommon>  {

  final List<SettingEntityReader> _readerList = RxList();
  StreamSubscription? actionSubscription;
  SettingEntity? entity;
  final box = GetStorage();

  var _psw = "000000";
  var _apiAddr = "192.168.2.100";
  // var _faceApiAddr = "http://192.168.2.100:10040";
  var _picApiAddr = "8.130.24.109";
  var _appKey = "rSZBWLfFlfjvYKunuqwSRvnY0ZlgUmfL0iZdjs4dpxf2fvZivQxQ4CP3f6OZIHsg";
  var _executable = "D:\\rfid_windows\\build\\windows\\runner\\Release";

  var _blockStart = 0;
  var _blockCount = 3;
  var _websocketAddr = "ws://localhost:10061";
  var _commonUid = "888888";
  int _slowCountdown = 300;
  int _normalCountdown = 120;
  int _fastCountdown = 20;
  int _scanTime = 4;
  double _scale1 = 2;
  double _scale2 = 2;
  double _translateX1 = 0;
  double _translateX2 = 0;
  double _translateY1 = 0;
  double _translateY2 = -20;
  var _auth = "1";
  var _deviceName = "轩毅";
  var _publishName = "轩毅";
  var _index = "1号柜";
  var _deviceNo = "device_id=rfid_cabinet_0001";
  var _kdApi = '10.113.1.11:18080';

  String _doorNo = "";
  String _readerIp = "";
  String _addr = "";
  String _ant = "";
  String _lock= "";
  var _fastAddr = '';
  var _fastAnts = '';
  var _fastIp = '';
  var _fastStartNo = '';
  final _analysisBook = 'xy'.obs;
  final _analysisReader = 'xy'.obs;
  final _canReturnIfOver = true.obs;
  final _face = 'xy'.obs;

  final List<DropdownMenuItem> _analysisBookRules =
  [
    const DropdownMenuItem(value: 'xy', child: Text('xy'),),
    const DropdownMenuItem(value: 'xm', child: Text('xm'),),
    const DropdownMenuItem(value: 'kd', child: Text('kd'),),
    const DropdownMenuItem(value: 'cz', child: Text('cz'),),
    const DropdownMenuItem(value: 'hfh', child: Text('hfh'),),
  ];
  final List<DropdownMenuItem> _analysisReaderRules =
  [
    const DropdownMenuItem(value: 'xy', child: Text('xy'),),
    const DropdownMenuItem(value: 'cz', child: Text('cz'),),
  ];

  final List<DropdownMenuItem> _faceRules =
  [
    const DropdownMenuItem(value: 'xy', child: Text('xy'),),
    const DropdownMenuItem(value: 'kd', child: Text('kd'),),
  ];

  @override
  initState() {
    super.initState();
    // box.remove("setting_entity");
    if(box.hasData('setting_entity')){
      entity = SettingEntity.fromJson(box.read("setting_entity"));
      if(entity!.reader != null && entity!.reader!.isNotEmpty){
        _readerList.addAll(entity!.reader!);
      }
      if(entity!.apiAddr != null){
        _apiAddr = entity!.apiAddr!;
      }
      if(entity!.executable != null){
        _executable = entity!.executable!;
      }
      if(entity!.face != null){
        _face.value = entity!.face!;
      }
      // if(entity!.faceApiAddr != null){
      //   _faceApiAddr = entity!.faceApiAddr!;
      // }
      if(entity!.picApiAddr != null){
        _picApiAddr = entity!.picApiAddr!;
      }
      if(entity!.kdApi != null){
        _kdApi = entity!.kdApi!;
      }
      if(entity!.index != null){
        _index = entity!.index!;
      }
      if(entity!.canReturnIfOver != null){
        _canReturnIfOver.value = entity!.canReturnIfOver!;
      }
      if(entity!.analysisBook != null){
        _analysisBook.value = entity!.analysisBook!;
      }
      if(entity!.analysisReader != null){
        _analysisReader.value = entity!.analysisReader!;
      }
      if(entity!.appKey != null){
        _appKey = entity!.appKey!;
      }
      if(entity!.webSocketAddr != null){
        _websocketAddr = entity!.webSocketAddr!;
      }
      if(entity!.slowCountdown != null){
        _slowCountdown = entity!.slowCountdown!;
      }
      if(entity!.normalCountdown != null){
        _normalCountdown = entity!.normalCountdown!;
      }
      if(entity!.fastCountdown != null){
        _fastCountdown = entity!.fastCountdown!;
      }
      if(entity!.auth != null){
        _auth = entity!.auth!;
      }
      if(entity!.deviceName != null){
        _deviceName = entity!.deviceName!;
      }
      if(entity!.scale1 != null){
        _scale1 = entity!.scale1!;
      }
      if(entity!.scale2 != null){
        _scale2 = entity!.scale2!;
      }
      if(entity!.translateX1 != null){
        _translateX1 = entity!.translateX1!;
      }
      if(entity!.translateX2 != null){
        _translateX2 = entity!.translateX2!;
      }
      if(entity!.translateY1 != null){
        _translateY1 = entity!.translateY1!;
      }
      if(entity!.translateY2 != null){
        _translateY2 = entity!.translateY2!;
      }
      if(entity!.publishName != null){
        _publishName = entity!.publishName!;
      }
      if(entity!.deviceNo != null){
        _deviceNo = entity!.deviceNo!;
      }
      if(entity!.commonUid != null){
        _commonUid = entity!.commonUid!;
      }
      if(entity!.psw != null){
        _psw = entity!.psw!;
      }
      if(entity!.isUltra != null){
        isUltra.value = entity!.isUltra!;
      }
      if(entity!.blockCount != null){
        _blockCount = entity!.blockCount!;
      }
      if(entity!.blockStart != null){
        _blockStart = entity!.blockStart!;
      }
      if(entity!.scanTime != null){
        _scanTime = entity!.scanTime!;
      }
    }else{
      entity = SettingEntity();
    }
    actionSubscription = eventFactory.on<InventoryRfidEvent>().listen((event) {
        BotToast.closeAllLoading();
        Get.defaultDialog(
          title: "",
          titlePadding:EdgeInsets.zero,
          middleText: event.entity.list != null?'盘点成功: ${event.entity.list!.length}本':"盘点失败",
          middleTextStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 6.sp,
          ),
          radius: 4.sp,
        );
    });

  }
  @override
  void dispose() {
    super.dispose();
    actionSubscription?.cancel();
    actionSubscription = null;
  }

  _itemWidget(index) {
    var item = _readerList[index];
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _listCell(item.doorNo,width: 30),
        _listCell(item.addr,width: 30),
        _listCell(item.lock,width: 30),
        _listCell(item.ant,width: 30),
        _listCell(item.readerIp,width: 75),
        SizedBox(width: 5.w,),
        Text('禁用', style: TextStyle(fontSize: 6.sp),),
        Switch(
          value: item.state == 0,
          onChanged: (value) {
            var books = bookQueryByDoorNo(item.doorNo!).where((element) => element.statue == 0);
            if(books.isNotEmpty){
              tts.speak( "请先通过图书整理下架柜内图书");
              toastWarn('请先通过图书整理下架柜内图书');
              return;
            }
            if( item.state == 0){
              item.state = 1;
            }else{
              item.state = 0;
            }
            _usefulReader(index,item.state);
          }
        ),
        Text('启用', style: TextStyle(fontSize: 6.sp),),
        Container(
            alignment: Alignment.center,
            width: 25.w,
            height: 15.h,
            child: TextButton(onPressed: () {
              _doorNo = item.doorNo??'';
              _ant = item.ant!;
              // _doorId = item.doorId!;
              _readerIp = item.readerIp!;
              _addr = item.addr!;
              _lock = item.lock!;
              _showReaderDialog(isEdit: true, index: index);
            }, child: Text('修改', style: TextStyle(fontSize: 6.sp),),)
        ),
        Container(
            alignment: Alignment.center,
            width: 25.w,
            height: 15.h,
            child: TextButton(onPressed: () {
              socketHelper.add(lockOpen(addr: item.addr!, no: item.lock!));
            }, child: Text('开门', style: TextStyle(fontSize: 6.sp),),)
        ),
        Container(
            alignment: Alignment.center,
            width: 25.w,
            height: 15.h,
            child: TextButton(onPressed: () {
              BotToast.showLoading();
              if(isUltra.value){
                socketHelper.add(inventoryUhfRfid(readerIp: item.readerIp!,ant: item.ant!,count: _scanTime));
              }else{
                socketHelper.add(inventoryHfRfid(readerIp: item.readerIp!,ant: item.ant!,count: _scanTime,blockStart:_blockStart,blockCount:_blockCount));
              }
            }, child: Text('盘点', style: TextStyle(fontSize: 6.sp),),)
        ),
        Container(
            alignment: Alignment.center,
            width: 25.w,
            height: 15.h,
            child: TextButton(onPressed: () {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      titlePadding:const EdgeInsets.only(top:10,left:40, right:40, bottom: 0).r,
                      title: const Text('确认删除', style: TextStyle(color: Colors.black)),
                      actions: [
                        TextButton(onPressed: () {
                          _delReaderEntity(index);
                          Get.back();
                        }, child: const Text('确定')),
                        TextButton(onPressed: () {
                          Get.back();
                        }, child: const Text('取消', style: TextStyle(color: Colors.black),)),
                      ],
                    );
                  });
            }, child: Text('删除', style: TextStyle(fontSize: 6.sp),),)
        ),
       ],
    );
  }


 _line(){
    return const Divider(height: 1.0,color: Colors.grey,);
 }

  _listCell(text,{int width = 90, int height =15, Color color =Colors.black }){
    return Container(
        alignment: Alignment.center,
        width: width.w,
        height: height.h,
        child: Text(text??'',style: TextStyle(color:color, fontSize: 6.sp))
    );
  }

  _labelRow(){
    return  Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _listCell("格口号",width: 30),
        _listCell("板地址",width: 30),
        _listCell("锁地址",width: 30),
        _listCell("天线号",width: 30),
        _listCell("读写器IP",width: 75),
      ],
    );
  }

  _faceWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  人脸接口  ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _face.value,
            onChanged: (value){
              _face.value = value.toString();
            },
            items: _faceRules,
          )),
        ),
        Text("  kdApi",   style: TextStyle(fontSize: 6.sp)),
        Container(
          width: 100.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _kdApi = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _kdApi,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _kdApi.length))
            )),
          ),
        ),
      ],
    );
  }

  _showReaderDialog({isEdit = false, index = 0}){
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          titlePadding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 40.w,right: 40.w),
          title: Column(
            children: [
              const Text('格口号', style: TextStyle(color: Colors.grey),),
              Container(
                width: 100.w,
                child: TextField(
                  decoration:  InputDecoration(
                    border:  const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                  ),
                  onChanged: (value){
                    _doorNo = value;
                  },
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _doorNo,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _doorNo.length))
                  )),
                ),
              ),
              SizedBox(height: 5.h,),
              const Text('板地址', style: TextStyle(color: Colors.grey),),
              Container(
                width: 100.w,
                child: TextField(
                  decoration:  InputDecoration(
                    border:  const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                  ),
                  onChanged: (value){
                    _addr = value;
                  },
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _addr,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _addr.length))
                  )),
                ),
              ),
              SizedBox(height: 5.h,),
              const Text('锁地址', style: TextStyle(color: Colors.grey),),
              Container(
                width: 100.w,
                child:  TextField(
                  decoration:  InputDecoration(
                    border:  const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                  ),
                  keyboardType: TextInputType.number,
                  onChanged: (value){
                    _lock = value;
                  },
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _lock,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _lock.length))
                  )),
                ),
              ),
              SizedBox(height: 5.h,),
              const Text('天线号', style: TextStyle(color: Colors.grey),),
              Container(
                width: 100.w,
                child:  TextField(
                  decoration:  InputDecoration(
                    border:  const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                  ),
                  onChanged: (value){
                    _ant = value;
                  },
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _ant,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _ant.length))
                  )),
                ),
              ),

              SizedBox(height: 5.h,),
              const Text('读写器IP', style: TextStyle(color: Colors.grey),),
              Container(
                width:100.w,
                child:  TextField(
                  decoration:  InputDecoration(
                    border:  const OutlineInputBorder(),
                    contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                  ),
                  onChanged: (value){
                    _readerIp = value;
                  },
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _readerIp,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _readerIp.length))
                  )),
                ),
              ),

            ],
          ),
          actions: [
            TextButton(onPressed: () {

              if( _addr.isEmpty ||_ant.isEmpty ||_doorNo.isEmpty || _readerIp.isEmpty || _lock.isEmpty){
                toastWarn('数据不能为空');
                return;
              }
              if(isEdit){
                _editReader(index);
              }else{
                _addReader();
              }

              Get.back();
            }, child: const Text('确定')),
            TextButton(onPressed: () {
              Get.back();
            }, child: const Text('取消', style: TextStyle(color: Colors.black),)),
          ],
        );
      });
  }


  _showFastSettingDialog(){
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            titlePadding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 40.w,right: 40.w),
            title: Column(
              children: [
                const Text('板地址', style: TextStyle(color: Colors.grey),),
                Container(
                  width: 100.w,
                  child: TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                    ),
                    onChanged: (value){
                      _fastAddr = value;
                    },
                    controller: TextEditingController.fromValue(TextEditingValue(
                        text: _fastAddr,
                        selection: TextSelection.fromPosition(
                            TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: _fastAddr.length))
                    )),
                  ),
                ),
                SizedBox(height: 5.h,),
                const Text('格口总数量', style: TextStyle(color: Colors.grey),),
                Container(
                  width: 100.w,
                  child:  TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                    ),
                    onChanged: (value){
                      _fastAnts = value;
                    },
                    controller: TextEditingController.fromValue(TextEditingValue(
                        text: _fastAnts,
                        selection: TextSelection.fromPosition(
                            TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: _fastAnts.length))
                    )),
                  ),
                ),
                SizedBox(height: 5.h,),
                const Text('格口起始编号', style: TextStyle(color: Colors.grey),),
                Container(
                  width: 100.w,
                  child:  TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                    ),
                    onChanged: (value){
                      _fastStartNo = value;
                    },
                    controller: TextEditingController.fromValue(TextEditingValue(
                        text: _fastStartNo,
                        selection: TextSelection.fromPosition(
                            TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: _fastStartNo.length))
                    )),
                  ),
                ),

                SizedBox(height: 5.h,),
                const Text('读写器IP', style: TextStyle(color: Colors.grey),),
                Container(
                  width:100.w,
                  child:  TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 0).r,
                    ),
                    onChanged: (value){
                      _fastIp = value;
                    },
                    controller: TextEditingController.fromValue(TextEditingValue(
                        text: _fastIp,
                        selection: TextSelection.fromPosition(
                            TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: _fastIp.length))
                    )),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(onPressed: () {

                if( _fastAddr.isEmpty ||_fastIp.isEmpty ||_fastAnts.isEmpty || _fastStartNo.isEmpty){
                  toastWarn('数据不能为空');
                  return;
                }
                _fastAddReader();

                Get.back();
              }, child: const Text('确定')),
              TextButton(onPressed: () {
                Get.back();
              }, child: const Text('取消', style: TextStyle(color: Colors.black),)),
            ],
          );
        });
  }

  _delReaderEntity(index){
    _readerList.removeAt(index);
    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());
    setState(() {

    });
  }

  _usefulReader(index,state){
    _readerList[index].state = state;
    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());
    setState(() {

    });
  }

  _editReader(index){
    _readerList[index].readerIp = _readerIp;
    _readerList[index].addr = _addr;
    _readerList[index].doorNo = _doorNo;
    _readerList[index].ant = _ant;
    _readerList[index].lock = _lock;
    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());
    setState(() {

    });
  }

  _fastAddReader(){
    for(int i = 1; i<=int.parse(_fastAnts);i++){
      var settingEntityReader = SettingEntityReader()
        ..addr = _fastAddr
        ..readerIp = _fastIp
        ..ant = i.toString()
        ..doorNo = '${int.parse(_fastStartNo)+i-1}'
        ..state = 0
        ..lock = i.toString();
      _readerList.add(settingEntityReader);
    }

    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());
  }

  _addReader(){

    var settingEntityReader = SettingEntityReader()
      ..addr = _addr
      ..readerIp = _readerIp
      ..ant = _ant
      ..doorNo = _doorNo
      ..state = 0
      ..lock = _lock;
    _readerList.add(settingEntityReader);
    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());
  }


  _apiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  服务器地址 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _apiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _apiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _apiAddr.length))
            )),
          ),
        ),
      ],
    );
  }


  // _faceWidget(){
  //   return Row(
  //     mainAxisAlignment: MainAxisAlignment.start,
  //     children: [
  //       Text("  人脸api地址 ",   style: TextStyle(fontSize: 6.sp),),
  //       Container(
  //         width: 200.w,
  //         height: 15.h,
  //         margin: EdgeInsets.all(5.r),
  //         child: TextField(
  //           decoration:  InputDecoration(
  //             border:  const OutlineInputBorder(),
  //             contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
  //           ),
  //           style: TextStyle(fontSize: 6.sp),
  //           onChanged: (value){
  //             _faceApiAddr = value;
  //           },
  //           controller: TextEditingController.fromValue(TextEditingValue(
  //               text: _faceApiAddr,
  //               selection: TextSelection.fromPosition(
  //                   TextPosition(
  //                       affinity: TextAffinity.downstream,
  //                       offset: _faceApiAddr.length))
  //           )),
  //         ),
  //       ),
  //     ],
  //   );
  // }
  //

  _picApiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  图片api地址 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _picApiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _picApiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _picApiAddr.length))
            )),
          ),
        ),
      ],
    );
  }

  _appKeyWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  appKey ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 250.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _appKey = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _appKey,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _appKey.length))
            )),
          ),
        ),
      ],
    );
  }

  RxBool isUltra = RxBool(false);


  _readerWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  (高频配置)起始块",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 20.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _blockStart = int.tryParse(value)??0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _blockStart.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _blockStart.toString().length))
            )),
          ),
        ),
        Text("  块数量",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 20.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _blockCount = int.tryParse(value)??0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _blockCount.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _blockCount.toString().length))
            )),
          ),
        ),
        Text("  高频",   style: TextStyle(fontSize: 6.sp),),
        Obx(() => Switch(
            value: isUltra.value,
            onChanged: (value) {
              isUltra.value = value;
            }
        ),),
        Text("超高频    ",   style: TextStyle(fontSize: 6.sp),),
        Text("盘点次数 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 20.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _scanTime = int.tryParse(value)??0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _scanTime.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _scanTime.toString().length))
            )),
          ),
        ),
      ],
    );
  }


  _websocketWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  websocket地址 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _websocketAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _websocketAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _websocketAddr.length))
            )),
          ),
        ),
      ],
    );
  }


  _commonUidWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  公用账户Id ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 100.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _commonUid = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _commonUid,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _commonUid.length))
            )),
          ),
        ),
        Text("  条码号解析规则 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _analysisBook.value,
            onChanged: (value){
              _analysisBook.value = value.toString();
            },
            items: _analysisBookRules,
          )),
        ),
        Text("  读者卡解析规则 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _analysisReader.value,
            onChanged: (value){
              _analysisReader.value = value.toString();
            },
            items: _analysisReaderRules,
          )),
        ),
      ],
    );
  }



  _countDownWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  倒计时配置(秒)：",   style: TextStyle(fontSize: 6.sp),),
        Text("  慢速",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 30.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _slowCountdown = int.tryParse(value)!;
              }

            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _slowCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _slowCountdown.toString().length))
            )),
          ),
        ),
        Text(" 常规 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 30.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _normalCountdown = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _normalCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _normalCountdown.toString().length))
            )),
          ),
        ),
        Text(" 快速 ",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 30.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _fastCountdown = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _fastCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _fastCountdown.toString().length))
            )),
          ),
        ),
      ],
    );
  }


  _authWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  输入对应数字,首位为默认(1=读者卡，2=身份证，3=人脸，4=二维码)",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _auth = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _auth,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _auth.length))
            )),
          ),
        ),
      ],
    );
  }


  _deviceNameWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备名",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 100.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _deviceName = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceName,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceName.length))
            )),
          ),
        ),
        Text("  设备号",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _index = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _index,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _index.length))
            )),
          ),
        ),
        focusKiller(),
        TextButton(onPressed: () {
          _saveDevice();
        }, child: Text('保存配置',   style: TextStyle(fontSize: 6.sp))),

      ],
    );
  }

  _publishNameWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  出版名",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _publishName = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _publishName,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _publishName.length))
            )),
          ),
        ),

        Text("  超限后可还",   style: TextStyle(fontSize: 6.sp),),
        Obx(() => Checkbox(
            side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
              return const BorderSide(width: 2);
            }),
            value: _canReturnIfOver.value,
            onChanged: (value){
              _canReturnIfOver.value = !_canReturnIfOver.value;
            }
        )),
      ],
    );
  }

  _deviceNoWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  sip2参数",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _deviceNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceNo,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceNo.length))
            )),
          ),
        ),
      ],
    );
  }


  _pswWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  管理员密码",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _psw = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _psw,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _psw.length))
            )),
          ),
        ),
      ],
    );
  }

  _cameraScaleWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  摄像头缩放1",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _scale1 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _scale1.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _scale1.toString().length))
            )),
          ),
        ),
        Text("  摄像头缩放2",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _scale2 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _scale2.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _scale2.toString().length))
            )),
          ),
        ),

      ],
    );
  }

  _cameraTranslateXWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  摄像头X轴偏移1",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _translateX1 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _translateX1.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _translateX1.toString().length))
            )),
          ),
        ),

        Text("  摄像头X轴偏移2",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _translateX2 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _translateX2.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _translateX2.toString().length))
            )),
          ),
        ),
      ],
    );
  }

  _cameraTranslateYWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  摄像头Y轴偏移1",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _translateY1 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _translateY1.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _translateY1.toString().length))
            )),
          ),
        ),

        Text("  摄像头Y轴偏移2",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 50.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _translateY2 = double.tryParse(value)??1.0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _translateY2.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _translateY2.toString().length))
            )),
          ),
        ),
      ],
    );
  }


  _executableWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  应用路径",   style: TextStyle(fontSize: 6.sp),),
        Container(
          width: 200.w,
          height: 15.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 6.sp),
            onChanged: (value){
              _executable = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _executable.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _executable.toString().length))
            )),
          ),
        ),
      ],
    );
  }

  _saveDevice(){
    entity!.deviceName = _deviceName;
    entity!.publishName = _publishName;
    entity!.deviceNo = _deviceNo;
    entity!.apiAddr = _apiAddr;
    entity!.picApiAddr = _picApiAddr;
    entity!.face = _face.value;
    entity!.kdApi = _kdApi;
    entity!.index = _index;
    entity!.canReturnIfOver = _canReturnIfOver.value;
    entity!.appKey = _appKey;
    entity!.webSocketAddr = _websocketAddr;
    entity!.slowCountdown = _slowCountdown;
    entity!.normalCountdown = _normalCountdown;
    entity!.fastCountdown = _fastCountdown;
    entity!.auth = _auth;
    entity!.commonUid = _commonUid;
    entity!.psw = _psw;
    entity!.isUltra = isUltra.value;
    entity!.analysisBook = _analysisBook.value;
    entity!.analysisReader = _analysisReader.value;
    entity!.blockStart = _blockStart;
    entity!.blockCount = _blockCount;
    entity!.scale1 = _scale1;
    entity!.scale2 = _scale2;
    entity!.translateX1 = _translateX1;
    entity!.translateX2 = _translateX2;
    entity!.translateY1 = _translateY1;
    entity!.translateY2 = _translateY2;
    entity!.scanTime = _scanTime;
    entity!.executable = _executable;
    box.write('setting_entity', entity!.toJson());
    toastWarn('保存成功');
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("配置"),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: (){

              if(box.hasData('setting_entity')){
                settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
              }
              Get.back();
            },
          ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _deviceNameWidget(),
          _publishNameWidget(),
          _deviceNoWidget(),
          _pswWidget(),
          _apiWidget(),
          _faceWidget(),
          _picApiWidget(),
          _appKeyWidget(),
          _websocketWidget(),
          _commonUidWidget(),
          _readerWidget(),
          _executableWidget(),
          _cameraScaleWidget(),
          _cameraTranslateXWidget(),
          _cameraTranslateYWidget(),
          _countDownWidget(),
          _authWidget(),
          Row(children: [
            TextButton(onPressed: () {
              _showReaderDialog();
            }, child: Text('新增格口',   style: TextStyle(fontSize: 6.sp))),
            TextButton(onPressed: () {
              _showFastSettingDialog();
            }, child: Text('快速配置',   style: TextStyle(fontSize: 6.sp))),
          ],),

          _labelRow(),
          _line(),
          Obx(() => Expanded(
            child: ListView.separated(
              itemBuilder: (BuildContext context, int index) {
                return _itemWidget(index);
              },
              separatorBuilder: (BuildContext context, int index) {
                return const Divider(height: 1.0, color: Colors.grey);
              },
              itemCount:  _readerList.length,
            )
          )),
        ],
      ),
    );
  }
}

